//
//  SearchView.m
//  LPlates.app
//
//  Created by Andreas Schwelling on 23.11.07.
//	http://www.andi.de/licenseplates/
//
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.


#import "SearchView.h"


@implementation SearchField

-(id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	
	
	return self;
}

- (bool)isEditing {
	
	[_delegate isEdited];
	[super isEditing];
	
}



@end


@implementation SearchView

-(void)fillTable
{
	
	_tableCells = [[NSMutableArray alloc] init];
	
	
	NSMutableArray *countiesarr =  [[NSMutableArray alloc] init];
	
	NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: @"/Applications/LPlates.app/default.plist"];
	
	NSArray *keys,*keys1;
	int k,j, count,count1;
	id key, value,  value1;
	
	keys = [dict allKeys];
	count = [keys count];
	
	int countycount = 0;
	
	for (j = 0; j < count; j++)
	  {
		  key = [keys objectAtIndex: j];
		  value = [dict objectForKey: key];
		  
		  keys1 = [value allKeys];
		  count1 = [keys1 count];
		  
		  
		  
		  NSDictionary *inner = [dict objectForKey: @"Countries"];
		  NSDictionary *inner1 = [inner objectForKey: [td getCountry]];
		  //NSLog (@"Key: %@ ", [inner1 allKeys] );
		  
		  
		  NSEnumerator *keyenum = [inner1 keyEnumerator];
		  
		  NSMutableArray *countiessorter = [[NSMutableArray alloc] init];
		  while ((key = [keyenum nextObject])) {
			  [countiessorter addObject: key];
		  }
		  
		  [countiessorter sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
		  
		  
		  id key;
		  int z = 0;
		  for(z=0;z<[countiessorter count];z++) {
			  //NSLog(@"%@",[countiessorter objectAtIndex:z]);
			  
			  
			  
			  NSDictionary *inner2 = [inner1 objectForKey:[countiessorter objectAtIndex:z]];
			  NSEnumerator *keyenum1 = [inner2 keyEnumerator];
			  id key1;
			  while ((key1 = [keyenum1 nextObject])) {
				  //if (key1 != @"STA") continue;
				  //		NSLog(@"%@ : %@", key1, [inner2 objectForKey:key1]);
				  NSDictionary *innerdic3 = [inner2 objectForKey:key1];
				  if ([innerdic3 objectForKey:@"depr"]) { continue;  }
				  [countiesarr addObject:key1];
				  countycount++;
				  
			  }
			  
			  [countiesarr sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
			  int i = 0;
			  for (i = 0;i < [countiesarr count];i++) {
				  ///
				  //NSString *strr = [@"aaa" uppercaseString];
				  //NSLog(@"%@",strr);//location,[countiesarr objectAtIndex:i]);
				  
				  
				  NSString *tosearch = [[searchField text] uppercaseString];
				  NSString *pliststr = [[countiesarr objectAtIndex:i] uppercaseString];
				  
				  if ([pliststr hasPrefix:tosearch]) {
					  
					  UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
					  [cell setTitle: [countiesarr objectAtIndex:i]];
					  [cell setDisclosureStyle:2];
					  [cell setShowDisclosure:YES animated:NO];
					  
					  
					  
					  [_tableCells addObject: cell]; 
					  [cell release];
					  
				  }
				  
			  }
			  
			  [countiesarr release];
			  countiesarr =  [[NSMutableArray alloc] init];
			  
			  
		  }
		  [countiessorter release];
	  }
	
	[countiesarr release];
	
}


- (void) dealloc
{
	
	[_tableCells release];
	[table release];
	[navBar release];
	[searchField release];
	[uip release];
	[super dealloc];
	
}

- (void)buildTable
{
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	table = [[UITable alloc] initWithFrame: CGRectMake(0.0f, 79.0f, 320.0f, 165.0f)];
	
	UITableColumn * packageColumn = [[UITableColumn alloc] initWithTitle:@"Title" identifier:@"title" width:320.0f];
	
	[table addTableColumn:packageColumn];
	[table setSeparatorStyle:1];
	[table setRowHeight:36.0f];
	[table setDelegate:self];
	[table setDataSource: self];
	[packageColumn release];
	
	
	//[self fillTable];
	//	cellDict = [[NSMutableDictionary alloc] initWithCapacity:2];
	//[cellDict setObject:@"B" forKey:@"title"];
	//[cellDict setObject:[[NSNumber alloc] initWithInt:10] forKey:@"beginRow"];
	
	//[_tableHeaders addObject: cellDict];
	
	//Refresh the fileview table
	
	
	[self addSubview:table];
	[self fillTable];
	
	
	
	[table reloadData];
}

-(void)refillTable:(id)p
{
	[self fillTable];
	[table reloadData];
	[uip stopAnimation];
}

-(void)isEdited
{
	NSString *searchFldStr = [searchField text];
	
	if ([searchFldStr isEqual:searchStr]) {  } else {
		//_tableCells = [[NSMutableArray alloc] init];
		searchStr = [searchFldStr copy];
		//NSLog(@"filling");
		[uip startAnimation];
		[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(refillTable:) userInfo:nil repeats:NO];
		
	}
	
}

-(id)initWithFrame:(CGRect)frame
{
	
	self = [super initWithFrame:frame];
	plistdict = [NSDictionary dictionaryWithContentsOfFile: @"/Applications/LPlates.app/default.plist"];
	td = [MobileVehicleRegPlates sharedInstance];
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	navBar = [[UINavigationBar alloc] init];
	[navBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 45.0f)];
	//[navBar showButtonsWithLeftTitle:@"Back" rightTitle:@"Search" leftBack:YES];
	[navBar showLeftButton:@"Back" withStyle:2 rightButton:@"Search" withStyle:1]; 
	[navBar setDelegate:self];
	[navBar enableAnimation];
	[navBar pushNavigationItem: [[UINavigationItem alloc] initWithTitle: @"Search"]];
	
	textView = [[UINavigationBar alloc] init];
	[textView setFrame:CGRectMake(0.0f, 45.0f, 320.0f, 35.0f)];
	[self addSubview:textView];
	
	struct __GSFont* font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:0 size:16];
	searchField = [[SearchField alloc] initWithFrame: CGRectMake(0.0f, 46.0f, 320.0f, 30.0f)];
	[searchField setFont:font];
	[searchField setClearButtonStyle:2];
	[searchField setText:@""];
	[searchField drawText:CGRectMake(0.0f, 1.0f, 320.0f, 20.0f)];
	[searchField setPaddingBottom:1.0f];
	[searchField setPaddingTop:5.0f];
	[searchField setDelegate:self];	
	//[searchField setTextAutorresizesToFit:YES];
	[searchField setVerticallyCenterText:NO];
	
	uip = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(270, 5, 20,20)];
	[uip setStyle:1];
	[uip stopAnimation];
	[searchField addSubview:uip];
	
	
	UIKeyboard*kb = [[UIKeyboard alloc] initWithFrame: CGRectMake(0.0f,243.0f,320.0f,216.0f)];	
	[searchField setAutoCapsType:0];
	[searchField setAutoCorrectionType:1];
	[searchField setReturnKeyType:6];
	//[searchField setPreferredKeyboardType: 4];
	[searchField setAutoEnablesReturnKey:YES];
	
	[self addSubview:navBar];
	[self addSubview:searchField];
	//	[searchField setNeedsDisplay];
	//NSLog(@"%@",[searchField text]);
	[searchField becomeFirstResponder];
	[self buildTable];
	[self addSubview: kb];
	[kb release];
	
	
	
	return self;
}


- (void)navigationBar:(UINavigationBar*)bar buttonClicked:(int)button
{
	if (button == 0) {
		[_delegate hideSearchView:1];
	} else {
		[_delegate hideSearchView:0];
	}
	
}

- (void)setDelegate: (id)delegate
{
    _delegate = delegate;
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
{
	
	return [_tableCells objectAtIndex: row];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
			   reusing: (BOOL) reusing
{
	//What does this message do?
    return nil;
}

- (int) numberOfRowsInTable: (UISectionTable*)table
{
	return [_tableCells count];
	
}

- (void) tableRowSelected: (NSNotification*) notification 
{
	//Get selected cell and filename
	UIImageAndTextTableCell* selectedCell = [_tableCells objectAtIndex: [table selectedRow]];
	[td setCounty:[selectedCell title]];
	
	[td setDescription:[selectedCell title]];
	[td setBeforeDetailView:self];
	[td showDetails:1];
	//Do stuff here...
}


@end